package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

type Consumer struct {
	workNo  int
	wg      *sync.WaitGroup //必须传指针，否则是复制一份
	imgPath string
	logger  *os.File
}

func (test *Consumer) Work(ch <-chan *sourceData, stop <-chan struct{}) {
	defer test.wg.Done()

	fmt.Printf("worker %d begin\n", test.workNo)
	for {
		select {
		case data := <-ch:
			//process data....
			test.deal(data)
		case <-stop:
			fmt.Printf("worker %d exit...", test.workNo)
			return
		}
	}
}

func (test *Consumer) deal(sd *sourceData) {
//	fmt.Println("deal: ", sd)

	url := sd.url
	if strings.HasPrefix(url, "http://") {
		if newFilename, err := test.downloadPicFromUrl(sd); err != nil {
			fmt.Printf("error: %v \n ",sd)
			fmt.Println(err)
			test.logger.WriteString(fmt.Sprintf("\n delete from common_image  where id = %s and image = '%s';\n", sd.id, sd.url))
			test.logger.WriteString(fmt.Sprintf("\n update instrument_instrument set manual_rating = 1 where manual_rating = 2 and id = %s ;\n", sd.objectId))
		} else {
			test.logger.WriteString(fmt.Sprintf("\n update common_image set image ='%s'  where id = %s and image = '%s';\n", newFilename, sd.id, sd.url))
		}
		test.logger.WriteString("")
	}else if strings.HasPrefix(url, "instrument_instrument") {
		test.logger.WriteString(fmt.Sprintf("\n update instrument_instrument set manual_rating = 3 where manual_rating = 2 and id = %s ;\n", sd.objectId))
		test.logger.WriteString("")
	}else {
		fmt.Printf("没有处理的数据： %v \n", sd)
	}

}

func (test *Consumer) downloadPicFromUrl(sd *sourceData) (string, error) {

	url := sd.url

	// 增加超时功能，否则 永久阻塞 就麻烦了。
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(netw, addr, time.Second*2)
				if err != nil {
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(time.Second * 5))
				return conn, nil
			},
			ResponseHeaderTimeout: time.Second * 15,
		},
	}

	time.Sleep(2*time.Second)

	res, err := client.Get(url)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	// 获得get请求响应的reader对象
	reader := bufio.NewReaderSize(res.Body, 32*1024)

	fileName := path.Base(url)
	if strings.Index(fileName,".") < 0 {
		fmt.Printf("没有后缀 %s：\n", fileName)
		fileName += ".png"
	}else{
		fmt.Printf("有后缀 ：%s \n", fileName)
	}

	newDir := filepath.Join(test.imgPath, "instrument_instrument", sd.objectId, "images")
	err = os.MkdirAll(newDir, os.ModePerm)
	if err != nil {
		return "", err
	}

	newFilenameInDB := filepath.Join("instrument_instrument", sd.objectId, "images", fileName)

	newFilename := filepath.Join(newDir, fileName)
	//newFilename := filepath.Join(test.imgPath,fmt.Sprintf("%d-%s",time.Now().Unix(),fileName))
	file, err := os.Create(newFilename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// 获得文件的writer对象
	writer := bufio.NewWriter(file)

	written, err := io.Copy(writer, reader)
	if err != nil {
		return "", err
	}
	err = writer.Flush()
	if err != nil {
		return "", err
	}

	if written <= 0 {
		return "", fmt.Errorf("空文件")
	}


	//fmt.Printf("Total length: %d", written)

	return strings.Replace(newFilenameInDB, "\\", "/", -1), nil
}
